<template>
  <div class="student-activity-list">
    <!-- 学生端只有两个选项卡 -->
    <div class="tab-header">
      <div class="activity-tabs">
        <el-radio-group v-model="activeTab" size="large">
          <el-radio-button label="all">所有活动</el-radio-button>
          <el-radio-button label="participated">我参与的</el-radio-button>
        </el-radio-group>
      </div>
    </div>

    <!-- 所有活动、我参与的活动共用同一套UI结构 -->
    <div v-if="activeTab === 'all' || activeTab === 'participated'">
      <!-- 搜索区域 -->
      <div class="search-area single-line">
        <el-input
            v-model="searchParams.keyword"
            placeholder="搜索活动名称"
            clearable
            class="search-input"
            @keyup.enter="handleSearch"
        />

        <el-select
            v-model="searchParams.baseId"
            placeholder="全部基地"
            clearable
            class="base-select"
        >
          <el-option label="全部基地" value="" />
          <el-option
              v-for="base in activityBases"
              :key="base.id"
              :label="base.name"
              :value="base.id"
          />
        </el-select>

        <el-select
            v-model="searchParams.fee"
            placeholder="收费类型"
            clearable
            class="fee-select"
        >
          <el-option label="全部" value="" />
          <el-option label="免费" value="free" />
          <el-option label="收费" value="paid" />
        </el-select>

        <el-button
            type="primary"
            @click="handleSearch"
            class="search-btn"
            :loading="loading"
        >
          <el-icon><Search /></el-icon>
          搜索
        </el-button>

        <el-button
            @click="handleReset"
            class="reset-btn"
        >
          重置
        </el-button>
      </div>

      <!-- 活动列表 -->
      <div class="activity-list">
        <div
            v-for="(activity, index) in displayedActivities"
            :key="activity.id || index"
            class="activity-item"
        >
          <div class="activity-image">
            <el-image
                :src="getDefaultImage(activity)"
                fit="cover"
                class="image-content"
            >
              <template #error>
                <div class="image-error">
                  <el-icon><Picture /></el-icon>
                </div>
              </template>
            </el-image>
          </div>

          <div class="activity-content">
            <h3 class="activity-title">{{ activity.title }}</h3>
            <div class="activity-details">
              <div class="detail-item">
                <span class="detail-label">基地：</span>
                <span>{{ getBaseName(activity.baseId) }}</span>
              </div>
              <div class="detail-item">
                <span class="detail-label">地址：</span>
                <span>{{ activity.address || '未设置' }}</span>
              </div>
              <div class="detail-item">
                <span class="detail-label">活动时间：</span>
                <span>{{ formatDate(activity.startDate) }} 至 {{ formatDate(activity.endDate) }}</span>
              </div>
              <div class="detail-item">
                <span class="detail-label">预约截止：</span>
                <span>{{ formatDateTime(activity.registrationDeadline) }}</span>
              </div>
              <div class="detail-item">
                <span class="detail-label">预约对象：</span>
                <span>{{ activity.targetAudience || '全体师生' }}</span>
              </div>
              <div class="detail-item">
                <span class="detail-label">是否收费：</span>
                <span :class="{ 'free': activity.isFree }">
                  {{ activity.isFree ? '免费' : '收费' }}
                </span>
              </div>
              <div class="detail-item">
                <span class="detail-label">发布时间：</span>
                <span>{{ formatDateTime(activity.publishTime) }}</span>
              </div>
              <div class="detail-item">
                <span class="detail-label">活动描述：</span>
                <span class="activity-description">{{ activity.description || '无描述' }}</span>
              </div>
            </div>
          </div>

          <div class="activity-action">
            <div class="signup-info">
              <div class="signup-count">
                {{ activity.currentParticipants || 0 }}人报名
              </div>
              <div class="signup-limit">
                人数限制：{{ activity.maxParticipants || '不限' }}人
              </div>
              <div class="contact-info">
                <div class="contact-item">
                  <el-icon><Phone /></el-icon>
                  {{ activity.creatorPhone || '未提供' }}
                </div>
                <div class="contact-item">
                  <el-icon><User /></el-icon>
                  {{ activity.creatorName || '未提供' }}
                </div>
                <div class="contact-item" v-if="activity.creatorEmail">
                  <el-icon><Message /></el-icon>
                  {{ activity.creatorEmail }}
                </div>
              </div>
            </div>

            <!-- 所有活动页面显示报名按钮 -->
            <el-button
                class="signup-btn"
                :type="getButtonType(activity)"
                :disabled="isButtonDisabled(activity)"
                @click="handleSignup(activity)"
                v-if="activeTab === 'all'"
                :loading="activity.signingUp"
            >
              {{ getButtonText(activity) }}
            </el-button>

            <!-- 我参与的页面，按钮显示为已报名 -->
            <el-button
                class="signup-btn"
                type="success"
                disabled
                v-else-if="activeTab === 'participated'"
            >
              已报名
            </el-button>
          </div>
        </div>

        <el-empty v-if="displayedActivities.length === 0" :description="getEmptyDescription()" />
      </div>

    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue';
import { Search, Picture, Phone, User, Message } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';

// 导入学生端API - 注意这里导入了getJoinedActivities
import {
  getAllActivities,
  getJoinedActivities,
  studentSignupActivity,
  getActivityBases
} from '@/api/student';

// 选项卡状态
const activeTab = ref('all');

// 真实数据
const activityBases = ref([]);
const allActivities = ref([]); // 所有活动数据
const participatedActivities = ref([]); // 我参与的活动数据
const loading = ref(false);

// 搜索参数
const searchParams = ref({
  keyword: '',
  baseId: '',
  fee: ''
});

// 计算属性 - 根据当前选项卡显示对应的活动（移除分页逻辑）
const displayedActivities = computed(() => {
  if (activeTab.value === 'all') {
    return allActivities.value;
  } else if (activeTab.value === 'participated') {
    return participatedActivities.value;
  }
  return [];
});

// 获取空状态描述文字
const getEmptyDescription = () => {
  if (activeTab.value === 'all') {
    return '暂无相关活动';
  } else if (activeTab.value === 'participated') {
    return '暂无参与的活动';
  }
  return '暂无数据';
};

// 方法
const handleSearch = async () => {
  await loadData();
};

const handleReset = async () => {
  searchParams.value = {
    keyword: '',
    baseId: '',
    fee: ''
  };
  await loadData();
};

// 报名按钮逻辑
const getButtonType = (activity: any) => {
  if (activity.hasJoined) {
    return 'success'; // 已报名 - 绿色
  } else if (isRegistrationDeadlinePassed(activity)) {
    return 'info'; // 报名截止 - 灰色
  } else {
    return 'primary'; // 立即报名 - 蓝色
  }
};

const isButtonDisabled = (activity: any) => {
  return activity.hasJoined || isRegistrationDeadlinePassed(activity) || activity.signingUp;
};

const getButtonText = (activity: any) => {
  if (activity.hasJoined) {
    return '已报名';
  } else if (isRegistrationDeadlinePassed(activity)) {
    return '报名截止';
  } else if (activity.signingUp) {
    return '报名中...';
  } else {
    return '立即报名';
  }
};

// 检查报名是否截止
const isRegistrationDeadlinePassed = (activity: any) => {
  const deadline = activity.registrationDeadline;
  if (!deadline) return false;

  const now = new Date();
  const deadlineDate = new Date(deadline);
  return now > deadlineDate;
};

// 根据基地ID获取基地名称
const getBaseName = (baseId: number) => {
  const base = activityBases.value.find((b: any) => b.id === baseId);
  return base ? base.name : '未知基地';
};

// 获取默认图片
const getDefaultImage = (activity: any) => {
  const defaultImages = [
    'https://fuss10.elemecdn.com/a/3f/3302e58f9a181d2509f3dc0fa68b0jpeg.jpeg',
    'https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg',
    'https://fuss10.elemecdn.com/1/34/19aa98b1fcb2781c4fba33d850549jpeg.jpeg'
  ];
  const index = activity.id ? activity.id % defaultImages.length : 0;
  return defaultImages[index];
};

// 处理报名 - 学生端版本
const handleSignup = async (activity: any) => {
  try {
    // 检查是否已报名
    if (activity.hasJoined) {
      ElMessage.warning('您已报名此活动');
      return;
    }

    // 检查报名是否截止
    if (isRegistrationDeadlinePassed(activity)) {
      ElMessage.warning('报名已截止');
      return;
    }

    // 检查人数是否已满
    if (activity.currentParticipants >= activity.maxParticipants) {
      ElMessage.warning('该活动报名人数已满');
      return;
    }

    // 显示确认弹窗
    try {
      await ElMessageBox.confirm(
          `确定要报名【${activity.title}】吗？`,
          '报名确认',
          {
            app: undefined,
            components: undefined,
            config: undefined,
            directives: undefined,
            mixins: [],
            provides: undefined,
            confirmButtonText: '确定报名',
            cancelButtonText: '取消',
            type: 'warning'
          }
      );
    } catch (cancel) {
      ElMessage.info('已取消报名');
      return;
    }

    // 用户确认报名，调用报名API
    const userInfoStr = localStorage.getItem('userInfo');
    const userInfo = userInfoStr ? JSON.parse(userInfoStr) : { id: 0 };

    if (!userInfo.id) {
      ElMessage.error('请先登录');
      return;
    }

    // 设置报名中状态
    activity.signingUp = true;

    const result = await studentSignupActivity(userInfo.id, activity.id);

    if (result.success) {
      ElMessage.success(`已成功报名【${activity.title}】`);

      // 更新活动状态
      activity.hasJoined = true;
      activity.currentParticipants = (activity.currentParticipants || 0) + 1;

      // 重新加载数据以更新状态
      await loadData();
    } else {
      ElMessage.error(result.message || '报名失败，请重试');
    }

  } catch (error) {
    console.error('报名失败:', error);
    ElMessage.error('报名失败，请重试');
  } finally {
    activity.signingUp = false;
  }
};

// 格式化日期时间
const formatDate = (dateString: string) => {
  if (!dateString) return '未设置';
  try {
    const date = new Date(dateString);
    return `${date.getFullYear()}-${padZero(date.getMonth() + 1)}-${padZero(date.getDate())}`;
  } catch (e) {
    return '日期格式错误';
  }
};

const formatDateTime = (datetime: string) => {
  if (!datetime) return '未设置';
  try {
    const date = new Date(datetime);
    return `${date.getFullYear()}-${padZero(date.getMonth() + 1)}-${padZero(date.getDate())} ${padZero(date.getHours())}:${padZero(date.getMinutes())}`;
  } catch (e) {
    return '时间格式错误';
  }
};

const padZero = (num: number) => {
  return num < 10 ? `0${num}` : num;
};

// 加载所有活动数据
const loadAllActivities = async () => {
  loading.value = true;
  try {
    const userInfoStr = localStorage.getItem('userInfo');
    const userInfo = userInfoStr ? JSON.parse(userInfoStr) : { id: 0 };

    if (!userInfo.id) {
      ElMessage.error('请先登录');
      return;
    }

    const activitiesRes = await getAllActivities(
        userInfo.id,
        searchParams.value.keyword,
        searchParams.value.baseId,
        searchParams.value.fee
    );

    if (activitiesRes.success) {
      // 移除分页逻辑，直接使用返回的数据
      allActivities.value = activitiesRes.data.list || activitiesRes.data || [];
    }
  } catch (error) {
    console.error('加载所有活动失败:', error);
    ElMessage.error('数据加载失败');
  } finally {
    loading.value = false;
  }
};

// 加载我参与的活动数据 - 使用getJoinedActivities API
const loadParticipatedActivities = async () => {
  loading.value = true;
  try {
    const userInfoStr = localStorage.getItem('userInfo');
    const userInfo = userInfoStr ? JSON.parse(userInfoStr) : { id: 0 };

    if (!userInfo.id) {
      ElMessage.error('请先登录');
      return;
    }

    const activitiesRes = await getJoinedActivities(
        userInfo.id,
        searchParams.value.keyword,
        searchParams.value.baseId,
        searchParams.value.fee
    );

    if (activitiesRes.success) {
      // 移除分页逻辑，直接使用返回的数据
      participatedActivities.value = activitiesRes.data.list || activitiesRes.data || [];
    }
  } catch (error) {
    console.error('加载参与活动失败:', error);
    ElMessage.error('加载参与活动失败');
  } finally {
    loading.value = false;
  }
};

// 加载数据
const loadData = async () => {
  // 加载基地列表（只需要加载一次）
  if (activityBases.value.length === 0) {
    const basesRes = await getActivityBases();
    if (basesRes.success) {
      activityBases.value = basesRes.data;
    }
  }

  // 根据当前选项卡加载对应的数据
  if (activeTab.value === 'all') {
    await loadAllActivities();
  } else if (activeTab.value === 'participated') {
    await loadParticipatedActivities();
  }
};

// 监听选项卡变化
watch(activeTab, () => {
  loadData();
});

// 初始化数据
onMounted(async () => {
  await loadData();
});
</script>

<style scoped>
.student-activity-list {
  padding: 15px;
}

.tab-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.activity-tabs {
  flex-grow: 1;
  margin-bottom: 20px;
  display: flex;
  justify-content: center;
}

.search-area.single-line {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
  align-items: center;
  justify-content: center;
}

.search-area.single-line .search-input {
  width: 200px;
}

.search-area.single-line .base-select {
  width: 180px;
}

.search-area.single-line .fee-select {
  width: 120px;
}

.search-area.single-line .search-btn {
  margin-left: 5px;
}

.reset-btn {
  margin-left: 10px;
}

.activity-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
  min-height: 500px;
}

.activity-item {
  display: flex;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  overflow: hidden;
}

.activity-image {
  width: 30%;
  height: 180px;
  background-color: #f5f7fa;
}

.image-content {
  width: 100%;
  height: 100%;
}

.image-error {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #c0c4cc;
}

.activity-content {
  width: 50%;
  padding: 15px;
}

.activity-title {
  margin: 0 0 10px 0;
  font-size: 16px;
  color: #333;
}

.activity-details {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 8px;
}

.detail-item {
  font-size: 13px;
  color: #606266;
  display: flex;
}

.detail-label {
  color: #909399;
  white-space: nowrap;
}

.activity-description {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.free {
  color: var(--el-color-success);
}

.activity-action {
  width: 20%;
  padding: 15px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  border-left: 1px solid #eee;
}

.signup-info {
  margin-bottom: 10px;
}

.signup-count {
  font-size: 16px;
  color: var(--el-color-primary);
  margin-bottom: 5px;
}

.signup-limit {
  font-size: 12px;
  color: #909399;
  margin-bottom: 10px;
}

.contact-info {
  font-size: 12px;
  color: #606266;
}

.contact-item {
  display: flex;
  align-items: center;
  margin-bottom: 5px;
}

.contact-item .el-icon {
  margin-right: 5px;
  font-size: 14px;
}

.signup-btn {
  width: 100%;
}

.empty-content {
  height: 500px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

@media (max-width: 992px) {
  .activity-item {
    flex-direction: column;
  }

  .activity-image,
  .activity-content,
  .activity-action {
    width: 100%;
  }

  .activity-action {
    border-left: none;
    border-top: 1px solid #eee;
    padding-top: 15px;
  }

  .search-area.single-line {
    flex-wrap: wrap;
  }

  .search-area.single-line .search-input,
  .search-area.single-line .base-select,
  .search-area.single-line .fee-select {
    width: 100%;
  }

  .search-area.single-line .search-btn,
  .search-area.single-line .reset-btn {
    width: 100%;
    margin-left: 0;
  }
}

@media (max-width: 768px) {
  .tab-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
}
</style>
